//帖子范文
var exampleWord = [
	'冰心奶奶，还是很值得尊敬的，不得不佩服她文字中的恬静和童真。你需要用一颗懂得的心，会发现那不是造作，是发自肺腑的真心情', 
	'坐在成片成片盛开满爬山虎的窗户上，一个小个子孩子撒着脚丫，慵懒的哼唱着不成腔调的歌曲，一双浅蓝色的眸子漫无目的地打着转，圆润的脸颊上长满棕色的雀斑。他叫彼得潘。是个骄傲的英雄。要怎么说呢，就如同那个时代熠熠生辉的古典骑士，在他的身上有着永远不会失色的品质。他永远都不会长大，纯真的心灵让他可以像故事里那样随意飞翔。他叫彼得潘。是个骄傲的英雄。', 
	'跟大家分享下你的绘画作品吧', 
	'画图有助思考哦', 
	'冰心奶奶在这本书的一篇里写道，她很喜欢大海，也非常喜欢海边的小动物，同样，也很爱护它们。她在回复小读者的时候，曾说起过这样一件事。有一天，冰心奶奶正在海边上呼吸着新鲜的空气，忽然看见一只海鸟在海里，不飞向天空，她很疑惑，海鸟都在天空中自由自在地翱翔，为什么只有这只海鸟不飞呢?于是，就走了过去，原来鸟的羽毛被一些东西刮伤了。于是，她就找来了一些可以处理伤口的东西，细心料理这只海鸟，海鸟慢慢好了，又可以到天空中飞翔了，冰心奶奶由衷地笑了。冰心奶奶的爱让我深深地感动了。'	
	]

var voiceTip =['此功能只能在微信端使用']//新加的朗读背诵按钮提示信息

    //项目相对路径
var path = $('input[type="hidden"]').val();
//从地址栏获取topicId还有bookId,split分割字符串与替换字符串
var searchKeyArray = window.location.search.replace(/\?/, '').split('&'),
    topicId = '',	
    bookId = '';

for (var i = 0, length = searchKeyArray.length; i < length; i++) {
    if (searchKeyArray[i].indexOf('topicId') != -1) {
        topicId = searchKeyArray[i].split('=')[1];
    }
    if (searchKeyArray[i].indexOf('bookId') != -1) {
        bookId = searchKeyArray[i].split('=')[1];
    }
}

$(function() {
    scalePic();
    conComment();
    formToggle();
    changeType();
    addPost();
    praise();
    lightNav();
    lightRank();
    deleteForumPost();
    querySchool();
    queryGrade();
    queryClass();
//    addFriendsList();
});

//缩放帖子绘画大小
function scalePic() {
    var pics = $('.post-content img');
    pics.click(function() {
        $(this).toggleClass('big');
    });
}

//展开收起较长评论
function conComment() {
    var comments = $('.post-content p');
    comments.each(function(index, element) {
        var height = $(this).height();
        //帖子内容超过一定宽度出现展开按钮
        if (height > 84) {
            var commentToggle = $(this).parent().siblings('.post-footer').find('.open');
            commentToggle.css({
                'display': 'inline-block',
            });
            commentToggle.open = false;
            commentToggle.click(function(event) {
                $(element).toggleClass('autoHeight');
                if (this.open === false) {
                    $(this).text('展开');
                    this.open = true;
                } else {
                    $(this).text('收起');
                    this.open = false;
                }
            });
        }
    })
};

// 发表表单开关
function formToggle() {
    var closeBtn = $('.close'),
        popup = $('.popup'),
        tip = popup.find('.tip'),
        popupType = popup.find('.typeTip'),
        openBtns = $('.main-head-addBtns button'),            
        imgFile = $('#imgFile'),
        content = $('.content');
    closeBtn.click(function() {
        tip.css('display', 'none');
        popup.slideUp();
        //popup.css('display', 'none');
    });
    openBtns.each(function(index, el) {
        $(this).click(function() {
            //根据帖子类型，判断文件选择框是否该出现
            $(this).text() === '+ 绘画' || $(this).text() === '+ 读后感' || $(this).text() === '+ 思维导图' || $(this).text() === '+ 读书笔记'? imgFile.css('display', 'inline-block') : imgFile.css('display', 'none');
            popupType.text($(this).text());//标题显示
            if($(this).text() === '+ 读后感') tip.css('display', 'inline-block');
            //根据帖子类型，改变表单内容区域的placeholder
            content.prop('placeholder', exampleWord[index]);
            popup.slideDown(600);         
        });
    });
}
//新加的朗读背诵按钮提示功能
$(".labgdu_beisong").click(function() {
	$('.popupL').show();
	$(".TipsMsg").slideDown();

});
//确认按钮
$('.cancelBack').click(function(){
	$('.popupL').hide();
	$(".TipsMsg").slideUp();
});

//更改url参数
function replaceParamVal(paramName,replaceWith) {
    var oUrl = this.location.href.toString();
    var re=eval('/('+ paramName+'=)([^&]*)/gi');
    var nUrl = oUrl.replace(re,paramName+'='+replaceWith);
    return nUrl;
};
//获取url某个属性
function GetQueryString(name)
{
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
};
//删除url某个参数
function funcUrlDel(name){
    var loca = window.location;
    var baseUrl = loca.origin + loca.pathname + "?";
    var query = loca.search.substr(1);
    if (query.indexOf(name)>-1) {
        var obj = {}
        var arr = query.split("&");
        for (var i = 0; i < arr.length; i++) {
            arr[i] = arr[i].split("=");
            obj[arr[i][0]] = arr[i][1];
        };
        delete obj[name];
        var url = baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g,"").replace(/\:/g,"=").replace(/\,/g,"&");
        return url;
    };
};
//类型切换
function changeType() {
    var catBtns = $('.main-category button'),
        typeArray = ['forum_post_pinglun', 'forum_post_duhougan', 'forum_post_huihua', 'forum_post_siwei', 'forum_post_biji','forum_post_langsong','forum_post_beisong'];
    catBtns.click(function(){
    	var index = $(this).index();
    	if(GetQueryString("postType") == null){
			if(index != 0){
				window.location.href = window.location.href + "&postType=" + typeArray[index - 1];
	    	}
    	}else{
	    	if(index == 0){
	    		window.location.href = funcUrlDel("postType");
	    	}else{
	    		window.location.href = replaceParamVal("postType",typeArray[index - 1]);
	    	}
    	}
    })
//    catBtns.each(function(index, element) {
//    	catBtns[index].click(function(){
//    		if (index == 0) {
//    			consol.log(0);
////                $(this).prop('href', path + '/forum/detail?topicId=' + topicId + '&bookId=' + bookId);
//            } else {
//            	console.log(typeArray[index - 1]);
////                $(this).prop('href', path + '/forum/detail?topicId=' + topicId + '&postType=' + typeArray[index - 1] + '&bookId=' + bookId);
//            }
//    	})
//    });
}

//评论的排序方式
var sortBtns = $('.post-sort a');
sortBtns.click(function(){
	var rank = $(this).attr("id");
	var href = window.location.href;
	var num = href.indexOf("rank");
	if(num == -1){
		href = href + "&rank=" + rank;
	}else{
		href = href.substring(0,num) + "rank=" + rank;
	}
	window.location.href = href;
})

//ajax发表帖子
function addPost() {
    var popUp = $('.popup'),
        addForm = $('.popup form'),
        title = addForm.find('.title'),
        content = addForm.find('.content'),
        imgFile = $('#imgFile'),
        type = addForm.find('.typeTip'),
        submitBtn = addForm.find('.submit'),
        inform = $('.inform'),
        agreeBtn = $('#agree'),
        haoci=$('.haoci'),
        jiaju=$('.jiaju');
    imgFile.change(function() {
        if (this.files[0].size > 10485760) {
            alert('所选文件大小不能超过10M');
            $(this).val('');
        }
    });
    addForm.submit(function() {
        if (!agreeBtn.prop('checked')) {
            alert('必须要经过家长同意才能发表哦');
            return false;
        }
        var gainScore = '',
            postType = '';
        switch (type.text()) {
            case '+ 短评':
                postType = 'forum_post_pinglun';
                gainScore = '1';
                break;
            case '+ 读后感':
                postType = 'forum_post_duhougan';
                gainScore = '3';
                break;
            case '+ 绘画':
                postType = 'forum_post_huihua';
                gainScore = '3';
                break;
            case '+ 思维导图':
                postType = 'forum_post_siwei';
                gainScore = '3';
                break;
            case '+ 读书笔记':
                postType = 'forum_post_biji';
                gainScore = '3';
                break;
        }
        //判空
        if (title.val().replace(/\s/g, '').length == 0) {
            alert('标题不能为空,请重新输入');
            return false;
        }
        if (content.val().replace(/\s/g, '').length == 0) {
            alert('内容不能为空,请重新输入');
            return false;
        }
        var fileName = imgFile.val();
        if (postType == 'forum_post_huihua' || postType == 'forum_post_siwei' || postType == 'forum_post_biji') {
            if (fileName == '') {
                alert('请选择文件');
                return false;
            }
        }
        //验证文件格式
        var extStart = fileName.lastIndexOf('.');
        var ext = fileName.substring(extStart, fileName.length).toUpperCase();
        if (ext != '.PNG' && ext != '.JPG' && ext != '.JPEG' && ext) {
            alert("只能选择格式为png,jpeg或者jpg的图片文件");
            return false;
        }
        $.ajaxFileUpload({
            url: path + '/forum/post/add',
            type: 'post',
            secureuri: false, //一般设置为false
            fileElementId: 'imgFile', // 上传文件的id、name属性名
            //dataType: 'json', //返回值类型，一般设置为json、application/json
            data: {
                "postTitle": title.val(),
                "postContent": content.val(),
                "postType": postType,
                "topicId": topicId
            },
            success: function(data) {
                if (data.data == "notget") {
                    inform.text('发表成功').slideDown();
                } else {
                    inform.text('发表成功,获得' + gainScore + '积分').slideDown();
                }
                setTimeout(function() {
                    window.location.reload();
                }, 1000);
            },
            error: function() {
                alert('error');
            }
        });
        popUp.fadeOut();
        return false;
    });
}

//ajax点赞
function praise() {
    var praiseBtn = $('.praise');
    praiseBtn.click(function(e) {
        var postId = $(this).siblings('.postId').text(),
            pNum = parseInt($(this).text());
        $.ajax({
            type: 'POST',
            url: path + "/forum/post/thumbUp",
            data: {
                postId: postId
            },
            cache: false,
//            dataType: 'json',
            success: function(result) {
                result.code == 200 ? $(e.target).parent().find('span').text((pNum + 1)) : alert('请勿在短时间内重复点赞同一帖子');
            },
            error: function() {
                alert('error！');
            }
        });
    });
}

//ajax删帖
function deleteForumPost() {
    $('.deleteForumPost').click(function(e) {
    	var postId = $(this).siblings('.postId').text();
        $.ajax({
            type: "POST",
            url: path + "/forum/post/delete",
            data: {
                postId: postId
            },
            dataType: "json",
            success: function(data) {
                alert('删除成功');
                setTimeout(function() {
                    window.location.reload();
                }, 1000);
            },
            error: function() {
                console.log('error!');
            }
        });
    });
}


/* 评论窗口的打开与关闭 */
var popup = $('.comment-popup');
var postId;
$('.commentForumPost').click(function() {
	popup.slideDown();
	postId = $(this).prev().text();
	//关闭评论窗口
	$('.comment-close').click(function() {
		popup.slideUp();
		$('.comment-userContent').val('');
	});
	
});
//发表评论按钮
popup.find("form button").eq(1).click(function(){
	var discussContent = $(".comment-userContent").val();
	if(discussContent == ''){
		alert("请输入你的评论")
	}else{
		$.ajax({
			type:"post",
			url: path + "/forum/post/addReply",
			data:{
				"postId":postId,
				"discussContent":discussContent
			},
			success(data){
				if(data.code == 200){
					alert("评论已发送");
					window.location.reload();
				}
			},
			error(data){
				console.log(data);
			}
		})
	}
	
	
});
/*回复评论窗口的打开与关闭 */
var popup2 = $('.reply-popup');



//隐藏或显示评论框
var discussId;//当前回复ID
$(".checkForumPost").click(function(){
	var ul = $(this).parent().prev().prev().children("ul");
	ul.empty();
	var postId = $(this).prev().prev().text();
	if($(this).next().val() == 0){
		ul.append("<p style=" + "text-align:center;" + ">暂无评论~</p>");
	}
	else{
		//发表评论
		$.ajax({
			type:"GET",
			url: path+ "/forum/post/detail",
			data:{
				"postId":postId
			},
			success(data){
				var list = data.dataList;
				$.each(list,function(i){
					var li;
					if(list[i].replyName != null){
						li = $(`<li class="comments-item">
			        			<div class="comments-content"> <span class="commentName">` + list[i].name + `</span>
			        				@<span class="replyName">` + list[i].replyName + `(` + list[i].replyDiscussContent +`)</span> : ` + list[i].discussContent +`
			            			<span style="display: none" class="discussId">`+ list[i].discussId +`</span> 
			            			<button class="reply-comments" >回复</button>
			        			</div>
			        		</li>`);
					}else{
						li = $(`<li class="comments-item">
			        			<div class="comments-content"><span class="commentName">` + list[i].name + `</span>
			        				: ` + list[i].discussContent +`
			            			<span style="display: none" class="discussId">`+ list[i].discussId +`</span> 
			            			<button class="reply-comments" >回复</button>
			        			</div>
			        		</li>`);
					}
					ul.append(li);
				});
				/*回复按钮显示与隐藏*/
				$(".comments-list ul li div").hover(function(){
					$(this).children("button").toggle();
				});
				$('.reply-comments').click(function() {
					popup2.slideDown();
					postId = $(this).parent().parent().parent().parent().next().children("span").text();
					discussId = $(this).prev().text();
					//关闭评论窗口
					$('.reply-close').click(function() {
						popup2.slideUp();
						$('.reply-userContent').val('');
					});
					
				});
			},
			error(data){
				console.log(data);
			}
		})
	}
	
	$(this).parent().prev().prev().toggle();
	if($(this).parent().prev().prev().is(":visible")){
		$(this).text("收起评论");
	}else{
		var num = $(this).next().val();
		$(this).text("查看评论(" + num + ")");
	};
	
});

//回复按钮
popup2.find("form button").eq(1).click(function(){
	postId = $(".reply-comments").parent().parent().parent().parent().next().children("span").text();
	var discussContent = $(".reply-userContent").val();
	var replyDiscussId = $(this).prev().text();
	if(discussContent == ''){
		alert("请输入评论")
	}else{
		$.ajax({
			type:"post",
			url: path + "/forum/post/addReply",
			data:{
				"postId":postId,
				"discussContent":discussContent,
				"replyDiscussId":discussId
			},
			success(data){
				if(data.code == 200){
					alert("评论已发送");
					window.location.reload();
				}
			},
			error(data){
				console.log(data);
			}
		})
	}
	
});

//学校、年级、班级页面跳转
function TypeHref(schoolId,gradeId,classId){
	var href = window.location.href;
	if(schoolId !== null){
		if(GetQueryString("gradeId") !== null){
			href = funcUrlDel("gradeId");
		}
		if(GetQueryString("classId") !== null){
			href = funcUrlDel("classId");
		}
		if(GetQueryString("schoolId") !== null){
			href = replaceParamVal("schoolId",schoolId);
		}else{
			href += "&schoolId="+schoolId;
		}
	}else if(gradeId !== null){
		if(GetQueryString("schoolId") !== null){
			href = funcUrlDel("schoolId");
		}
		if(GetQueryString("classId") !== null){
			href = funcUrlDel("classId");
		}
		if(GetQueryString("gradeId") !== null){
			href = replaceParamVal("gradeId",gradeId);
		}else{
			href += "&gradeId="+gradeId;
		}
	}else if(classId !== null){
		if(GetQueryString("schoolId") !== null){
			href = funcUrlDel("schoolId");
		}
		if(GetQueryString("gradeId") !== null){
			href = funcUrlDel("gradeId");
		}
		
		if(GetQueryString("classId") !== null){
			href = replaceParamVal("classId",classId);
		}else{
			href += "&classId="+classId;
		}
		
	}
	return href;
}

//获取所有学校
function querySchool() {
	var schoolSelect = $(".checkSelect .selectSchool");
	var gradeSelect = $(".checkSelect .selectGrade");
	var classSelect = $(".checkSelect .selectClass");
	$.ajax({
		type:"GET",
		url: path + "/forum/getSchoolList",
		dataType: "json",
		success :function(data){
//			schoolSelect.empty();
			if($(".selectSchool").val() != -1){
				var all = new Option("全部学校",-1)
				schoolSelect.append(all);
			}
			var schoolList = data.data;
			$.each(schoolList,function(i) {
				if(schoolList[i].schoolId != $(".selectSchool").val()){
					var school = new Option(schoolList[i].schoolName, schoolList[i].schoolId);
					schoolSelect.append(school);
				}
		    });
		},
		error: function(){
			console.log("error!");
		}
	});
	schoolSelect.change(function() {
		gradeSelect.empty();
		if($(".selectSchool").val() == -1){
			var allGrade = new Option("全部年级",-1);
			gradeSelect.append(allGrade);
			var allClass = new Option("全部班级","-1")
			classSelect.append(allClass);
			window.location.href=TypeHref($(".selectSchool").val(),null,null);
//			window.location.href=path + "/forum/detail?topicId="+topicId+"&bookId="+bookId+"&schoolId="+ $(".selectSchool").val();
		}
		queryGrade();   
	});
	
	gradeSelect.change(function(){
		classSelect.empty();
		if($(".selectGrade").val() == -1){
			var all = new Option("全部班级","-1")
			classSelect.append(all);			
			window.location.href=TypeHref($(".selectSchool").val(),null,null);
//			window.location.href=path + "/forum/detail?topicId="+topicId+"&bookId="+bookId+"&schoolId="+ $(".selectSchool").val();
		}
    	queryClass();
    });
	
    classSelect.change(function(){
    	if($(".selectClass").val() == "-1"){
    		window.location.href=TypeHref(null,$(".selectGrade").val(),null);
//    		window.location.href=path + "/forum/detail?topicId="+topicId+"&bookId="+bookId+"&gradeId="+ $(".selectGrade").val();
    	}else{
    		window.location.href=TypeHref(null,null,$(".selectClass").val());
//    		window.location.href=path + "/forum/detail?topicId="+topicId+"&bookId="+bookId+"&classId="+ $(".selectClass").val();
    	}
	});
}
//获取所有年级
function queryGrade() {
	var gradeSelect = $(".checkSelect .selectGrade");
	$.ajax({
		type:"GET",
		url: path + "/forum/getGradeList",
		data:{
			'schoolId' : $(".selectSchool").val()
		},
		dataType: "json",
		success :function(data){
			if($(".selectGrade").val() != -1){
				var all = new Option("全部年级",-1)
				gradeSelect.append(all);
			}
			var gradeList = data.data;
			$.each(gradeList,function(i) {
				if(gradeList[i].gradeId != $(".selectGrade").val()){
					var grade = new Option(gradeList[i].gradeName, gradeList[i].gradeId);
					gradeSelect.append(grade);
				}
		    });
		},
		error: function(){
			console.log("error!");
		}
	});
}
//获取所有班级
function queryClass() {
	var classSelect = $(".checkSelect .selectClass");
	$.ajax({
		type:"GET",
		url: path + "/forum/getClassList",
		data:{
			'gradeId' : $(".selectGrade").val()
		},
		dataType: "json",
		success :function(data){
			if($(".selectClass").val() != "-1"){
				var all = new Option("全部班级","-1")
				classSelect.append(all);
			}
			var classList = data.data;
			$.each(classList,function(i) {
				if(classList[i].classId != $(".selectClass").val()){
					var clazz = new Option(classList[i].className, classList[i].classId);
					classSelect.append(clazz);
				}
		    });
		},
		error: function(){
			console.log("error!");
		}
	});
}
//图片加载失败的时候删除图片
function errorDelete() {
    var pics = $('.pic');
    pics.bind('error', function() {
        $(this).remove();
    });
}

//高亮筛选按钮
function lightNav() {
    var pt = $('#pt').text();
    $('.' + pt).addClass('current');
}

//
function lightRank() {
    var rank = $('#rank').text();
    $('#' + rank).addClass('current');
}
//点击icon添加好友
$(function() {
	// 添加好友弹出框
	$('body').on("click", ".add-friend", function() {
		var url = $(this).data('url');
		var addUserId = $(this).attr('id');
		x0p({
			maxWidth : '520px',
			maxHeight : '292px',
			title : '确定加为好友么？',
			// text: '#',
			animationType : 'slideUp',
			icon : 'info',
			buttons : [ {
				type : 'info',
				text : '加为好友'
			}, {
				type : 'cancel',
				text : '取消'
			} ]
		}, function(button) {
			if (button === 'info') {
				$.ajax({
					url : path + "/userRelationship/addFriend",
					type : 'post',
					dataType : 'json',
					data : {
						userIdFriend : addUserId,
					},
					success : function(data) {
						if (data.data == "重复添加") {
							alert("重复添加");
						} else {
							alert("添加成功");
						}
					},
					error : function() {
						alert('error');
					}
				})
			}
		});
	});
});